from django.shortcuts import render
from .models import Doc
# Create your views here.
from django.views import View
from django.conf import settings
from django.http import FileResponse, Http404
import requests
import logging
logger = logging.getLogger('django')
from django.utils.encoding import escape_uri_path


def doc_index(request):
    docs = Doc.objects.defer('author','create_time','update_time','is_delete').filter(is_delete=False)
    return render(request,'doc/docDownload.html',locals())

# 书籍的下载
class DocDownload(View):
    """
    /doc/<int:doc_id>/
    """
    def get(self,request,doc_id):
        doc = Doc.objects.only('file_url').filter(is_delete=False,id=doc_id).first()
        if doc:
            doc_url = doc.file_url
            # doc_url = 'http://192.168.216.137:8888'  6789
            # 拼接路由
            if doc_url.split('/')[1] == 'media':
                doc_url = settings.SITE_DOMAIN_PORT + doc_url
            try:
                res = FileResponse(requests.get(doc_url, stream=True))
            except Exception as e:
                logger.info('获取文件内容异常：\n{}'.format(e))
                raise Http404('文件下载异常')
            # http://127.0.0.1:99/media/流畅的Python.pdf
            ex_name = doc_url.split('.')[-1]    # pdf
            if not ex_name:
                raise Http404('文件url异常')
            else:
                ex_name = ex_name.lower()
            if ex_name == "pdf":
                res["Content-type"] = "application/pdf"
            elif ex_name == "zip":
                res["Content-type"] = "application/zip"
            elif ex_name == "doc":
                res["Content-type"] = "application/msword"
            elif ex_name == "xls":
                res["Content-type"] = "application/vnd.ms-excel"
            elif ex_name == "docx":
                res["Content-type"] = "application/vnd.openxmlformats-officedocument.wordprocessingml.document"
            elif ex_name == "ppt":
                res["Content-type"] = "application/vnd.ms-powerpoint"
            elif ex_name == "pptx":
                res["Content-type"] = "application/vnd.openxmlformats-officedocument.presentationml.presentation"
            else:
                raise Http404('文件格式不存在')
            # 流畅的Python.pdf
            doc_filename = escape_uri_path(doc_url.split('/')[-1])
            res["Content-Disposition"] = "attachment; filename*=UTF-8''{}".format(doc_filename)
            return res
        else:
            raise Http404('文档不存在！！！')




